import os
import time
from datetime import datetime

from util.selenium.common.exceptions import TimeoutException
from util.selenium.webdriver.common.by import By

####     测试时使用base模块    __init__.py    文件中的driver, 运行测试代码时需注释，否则将会打开多个浏览器
from util.selenium.webdriver.support.wait import WebDriverWait

from base.BaseMethod import BM, alert_is_present
from PageObject.WriteRegistrationForm import WriteRegistrationForm
from util.DataQuery.hzflowOperation import hzflowOperation
from util.g import g
from settings import check_year, material_status




class CheckMaterialYearAndStatus():

    # top_frame_loc = (By.CSS_SELECTOR, 'iframe')

    main_frame_loc = (By.CSS_SELECTOR, 'iframe#mainFrame')

    year_loc = (By.CSS_SELECTOR, '.tableRegionDivBody table tbody tr:nth-child(1) td:nth-child(1)')

    creat_btn_loc = (By.CSS_SELECTOR, 'button.blue.pull-right.createBtn')

    status_loc = (By.CSS_SELECTOR, '.tableRegionDivBody table tbody tr:nth-child(1) td:nth-child(4)')

    modification_btn_loc = (By.CSS_SELECTOR, '.tableRegionDivBody table tbody tr:nth-child(1) td:nth-child(5) a:nth-child(1)')
    delete_btn_loc = (By.CSS_SELECTOR, ".tableRegionDivBody table tbody tr:nth-child(1) td:nth-child(5) a:nth-child(2)")

    current_year = check_year if check_year else time.strftime('%Y')

    #  编写代码时先将  __init__  方法注释，调试时记得打开
    def __init__(self, driver):
        self.driver = driver

    def get_year_text(self):
        BM.driver_wait(driver=self.driver, ele_loc=self.year_loc, time=10)
        return self.driver.find_element(*self.year_loc).text

    def click_creat_btn(self):
        BM.click(driver=self.driver, ele_loc=self.creat_btn_loc)

    def get_status_text(self):
        return self.driver.find_element(*self.status_loc).text

    def click_modification_btn(self):
        BM.click(driver=self.driver, ele_loc=self.modification_btn_loc)

    def check_material_year_and_status(self):
        self.driver.switch_to.default_content()

        BM.wait(driver=self.driver, ele_loc=self.main_frame_loc)

        # BM.cut_over_frame(self.driver, self.top_frame_loc)
        BM.cut_over_frame(self.driver, self.main_frame_loc)
        year = None
        try:
            year = self.get_year_text()
            # g.year = int(year) if type(year) == str else year
        except Exception as err:
            g.logger.error("get materials year error err: {}".format(err))

        delete = False
        if g.withdrow is True:
            if not year:
                pass
            else:
                try:
                    BM.click(driver=self.driver, ele_loc=self.delete_btn_loc, wait="driver_wait")
                    BM.alert_accept(driver=self.driver)
                    delete = True
                    g.logger.info("删除材料")
                    BM.alert_accept(driver=self.driver)
                except TimeoutException as err:
                    pass
                hzflowOperation.update_field(g.record, "withdrow_time", g.status.get("fb_time"))
                hzflowOperation.emptyProcess(co_id=g.co_id, year=g.year)
                g.record = hzflowOperation.get_log(co_id=g.co_id, year=g.year)

        if delete is not True and g.is_first_entry is True:
            try:
                BM.click(driver=self.driver, ele_loc=self.delete_btn_loc, wait="driver_wait")
                BM.alert_accept(driver=self.driver)
                BM.alert_accept(driver=self.driver)
                hzflowOperation.update_field_by_co_id(co_id=g.co_id, year=g.year, field_name="first_entry_delete",
                                                      field_value=1)
                g.logger.info("第一次录入删除")
                hzflowOperation.emptyProcess(co_id=g.co_id, year=g.year)
                g.record = hzflowOperation.get_log(co_id=g.co_id, year=g.year)
            except TimeoutException as err:
                pass
        year = None
        try:
            year = self.get_year_text()
            # g.year = int(year) if type(year) == str else year
        except Exception as err:
            g.logger.error("get materials year error err: {}".format(err))

        if not year or self.current_year != year:
            self.click_creat_btn()
            # TODO 等待弹框出现， 要求完善信息时将 注册登记表的部分信息录入
            # alert = WebDriverWait(driver=self.driver, timeout=30, poll_frequency=0.5).until(alert_is_present())

            g.logger.info("材料创建： year: -{}- self.current_year: -{}-".format(year, self.current_year))
            if BM.check_alert_and_get_text(driver=self.driver):
                g.year = datetime.now().year
                WriteRegistrationForm(driver=self.driver, perfect=True).main()
                self.click_creat_btn()
            return
        # if not g.withdrow:
            # BM.wait(driver=self.driver, ele_loc=self.status_loc)
        try:
            BM.driver_wait(driver=self.driver, ele_loc=self.status_loc)
        except TimeoutException as err:
            self.click_modification_btn()
            g.logger.error("材料状态信息未找到: {}".format(err))

        else:
            status = self.get_status_text()
            g.logger.info("材料状态: {}".format(status))

            if status != material_status.get('underway'):
                # #   TODO 当材料状态是 已报备 时，终止当前程序，登录下一个账号, 并将  hitech 数据库中的 ent_datasync 中 c_syncstatus 改为 1
                # #   TODO 实现一个全局变量类，当材料状态是 已报备 时， 将 is_exit 变量赋值为 TRUE， 在for循环中检测到 is_exit 为 True 时退出当前循环。
                hzflowOperation.update_host_process(obj=hzflowOperation.get_log(g.co_id, g.year), mark_info="")
                self.driver.quit()
                os._exit(0)

            if status == material_status.get('underway'):
                # print('点击了修改按钮')
                self.click_modification_btn()

